import axios from "axios";
import { Toast } from "@douyinfe/semi-ui";

axios.create({
  timeout: 5 * 1000, //60s的超时时间
  headers: {},
});

// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    const defaultToken = localStorage.getItem("token");
    config.headers["Authorization"] = "Bearer " + defaultToken;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.data.code != "00000") {
      if (response?.data?.msg.includes("token已失效")) {
        Toast.error(response.data.msg);
        location.href = "/";
        localStorage.removeItem("token");
        return;
      } else {
        Toast.error(response.data.msg);
      }
    }
    return response;
  },
  (error) => {
    const status = error.response?.status;
    if (error.config?.isErrorToast) {
      if (status == 401 || status == 403) {
        Toast.error(error.response.status);
      } else {
        Toast.error("服务异常");
      }
    }
    return error.response;
  },
);

/** 封装http请求 */
const request = {
  get: (url, options) => {
    return new Promise((resolve, reject) => {
      axios({
        isErrorToast: true,
        ...options,
        url: url,
        method: "get",
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err.data);
        });
    });
  },
  post: (url, options) => {
    const { data = {}, requestType } = options || {};
    if (requestType == "form") {
      const formData = new FormData();
      Object.keys(data).forEach((key) => {
        if (data[key]) {
          formData.append(key, data[key]);
        }
      });
      if (options) {
        options.data = formData;
      }
    }

    return new Promise((resolve, reject) => {
      axios({
        isErrorToast: true,
        ...options,
        url: url,
        method: "post",
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err.data);
        });
    });
  },
  put: (url, options) => {
    return new Promise((resolve, reject) => {
      axios({
        isErrorToast: true,
        ...options,
        url: url,
        method: "put",
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err.data);
        });
    });
  },
  delete: (url, options) => {
    return new Promise((resolve, reject) => {
      axios({
        isErrorToast: true,
        ...options,
        url: url,
        method: "delete",
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err.data);
        });
    });
  },
};

export default request;
